package Edges;
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import BasicTypes.Constants;
import BasicTypes.Position;
import BasicTypes.Table;

/**
 * This is an example Hadoop Map/Reduce application.
 * It reads the text input files, breaks each line into words
 * and counts them. The output is a locally sorted list of words and the
 * count of how often they occurred.
 *
 * To run: bin/hadoop jar build/hadoop-examples.jar wordcount
 *            [-m <i>maps</i>] [-r <i>reduces</i>] <i>in-dir</i> <i>out-dir</i>
 */
public class CountEdges extends Configured implements Tool {

  /**
   * Counts the words in each line.
   * For each line of input, break the line into words and emit them as
   * (<b>word</b>, <b>1</b>).
   */

	
  public static class MapClass extends MapReduceBase
    implements Mapper<LongWritable, Text, Text, Text> {
    
	private int GetNext(double test) {
		double fromNetID = 0.925;
		double desiredDensity = Constants.DENSITY;
		double wMin = 0.4 * fromNetID;
		//double wMin = 0.0;
		double wLimit = wMin + desiredDensity;
		return (((test >= wMin) && (test < wLimit)) ? 1 : 0);
	}
	
    public void map(LongWritable key, Text value,
                    OutputCollector<Text, Text> output,
                    Reporter reporter) throws IOException {
    	if(GetNext(Double.parseDouble(value.toString())) == 1){
    		int index = (int) (key.get()/Constants.KEYSIZE);
        	Position p = Table.getPosition(index);
        	if(p.y > 0){
        		Position below = new Position(p.x,p.y - 1);
        		output.collect(new Text(below.getString()), new Text(p.getString()));
        		if(p.x > 0){
            		Position belowleft = new Position(p.x - 1,p.y - 1);
            		output.collect(new Text(belowleft.getString()), new Text(p.getString()));
        		}
        		if(p.x < Constants.SIZE - 1){
            		Position belowright = new Position(p.x + 1,p.y - 1);
            		output.collect(new Text(belowright.getString()), new Text(p.getString()));
        		}
        	}
        	if(p.x > 0){
        		Position left = new Position(p.x -1 , p.y);
        		output.collect(new Text(left.getString()), new Text(p.getString()));
        	}
        	
        	output.collect(new Text(p.getString()), new Text(p.getString()));
    	}
    }
  }

  /**
   * A reducer class that just emits the sum of the input values.
   */
  public static class Reduce extends MapReduceBase
    implements Reducer<Text,Text,IntWritable,IntWritable> {

    public void reduce(Text key, Iterator<Text> value,
                       OutputCollector<IntWritable, IntWritable> output,
                       Reporter reporter) throws IOException {
		Position p = new Position(key.toString());
		Position right = new Position(p.x+1,p.y);
		Position up = new Position(p.x,p.y+1);
		Position upright = new Position(p.x + 1, p.y + 1);
		Position upleft = new Position(p.x - 1, p.y + 1);
		boolean bupright = false;
		boolean bupleft = false;
		boolean bright = false;
		boolean bup = false;
		boolean bself = false;
		while(value.hasNext()){
			Position temp = new Position(value.next().toString());
			if(temp.equals(p)){
				bself = true;
				continue;
			}
			if(temp.equals(right)){
				bright = true;
				continue;
			}
			if(temp.equals(up)){
				bup = true;
				continue;
			}
			
			if(temp.equals(upleft)){
				bupleft = true;
				continue;
			}
			if(temp.equals(upright)){
				bupright = true;
				continue;
			}
		}
		if(bself){
			if(bright){
				output.collect(new IntWritable(p.toNumber()), new IntWritable(right.toNumber()));
				//output.collect(new IntWritable(p.toNumber()), new IntWritable(BasicTypes.Constants.SIZE));
			}
			if(bup){
				output.collect(new IntWritable(p.toNumber()), new IntWritable(up.toNumber()));
			}
			
			if(bupleft){
				output.collect(new IntWritable(p.toNumber()), new IntWritable(upleft.toNumber()));
			}
			if(bupright){
				output.collect(new IntWritable(p.toNumber()), new IntWritable(upright.toNumber()));
			}
		}

    }
  }

  static int printUsage() {
    System.out.println("wordcount [-m <maps>] [-r <reduces>] <input> <output>");
    ToolRunner.printGenericCommandUsage(System.out);
    return -1;
  }

  /**
   * The main driver for word count map/reduce program.
   * Invoke this method to submit the map/reduce job.
   * @throws IOException When there is communication problems with the
   *                     job tracker.
   */
  public int run(String[] args) throws Exception {
    JobConf conf = new JobConf(getConf(), CountEdges.class);
    conf.setJobName("Edges");
    conf.setInputFormat(org.apache.hadoop.mapred.TextInputFormat.class);

 // CG_MAPPER_HIDDEN

 // CG_MAPPER
 conf.setMapOutputKeyClass(org.apache.hadoop.io.Text.class);
 conf.setMapOutputValueClass(org.apache.hadoop.io.Text.class);

 // CG_PARTITIONER_HIDDEN
 conf.setPartitionerClass(org.apache.hadoop.mapred.lib.HashPartitioner.class);

 // CG_PARTITIONER

 // CG_COMPARATOR_HIDDEN
 conf.setOutputKeyComparatorClass(org.apache.hadoop.io.Text.Comparator.class);

 // CG_COMPARATOR

 // CG_COMBINER_HIDDEN

 // CG_REDUCER_HIDDEN

 // CG_REDUCER
 //conf.setNumReduceTasks(1);
 conf.setOutputKeyClass(org.apache.hadoop.io.IntWritable.class);
 conf.setOutputValueClass(org.apache.hadoop.io.IntWritable.class);

 // CG_OUTPUT_HIDDEN
 conf.setOutputFormat(org.apache.hadoop.mapred.TextOutputFormat.class);

    // the keys are words (strings)
    //conf.setOutputKeyClass(Text.class);
    // the values are counts (ints)
    //conf.setOutputValueClass(IntWritable.class);
    //conf.setMapOutputKeyClass(theClass)
    //conf.
    conf.setMapperClass(MapClass.class);
    //conf.setCombinerClass(Reduce.class);
    conf.setReducerClass(Reduce.class);
    //conf.setNumReduceTasks();
    List<String> other_args = new ArrayList<String>();
    for(int i=0; i < args.length; ++i) {
      try {
        if ("-m".equals(args[i])) {
          conf.setNumMapTasks(Integer.parseInt(args[++i]));
        } else if ("-r".equals(args[i])) {
          conf.setNumReduceTasks(Integer.parseInt(args[++i]));
        } else if("-c".equals(args[i])){
          Constants.DENSITY = Double.parseDouble(args[++i]);
        } else {
          other_args.add(args[i]);
        }
      } catch (NumberFormatException except) {
        System.out.println("ERROR: Integer expected instead of " + args[i]);
        return printUsage();
      } catch (ArrayIndexOutOfBoundsException except) {
        System.out.println("ERROR: Required parameter missing from " +
                           args[i-1]);
        return printUsage();
      }
    }
    // Make sure there are exactly 2 parameters left.
    if (other_args.size() != 2) {
      System.out.println("ERROR: Wrong number of parameters: " +
                         other_args.size() + " instead of 2.");
      return printUsage();
    }
    FileInputFormat.setInputPaths(conf, other_args.get(0));
    FileOutputFormat.setOutputPath(conf, new Path(other_args.get(1)));

    JobClient.runJob(conf);
    return 0;
  }


  public static void main(String[] args) throws Exception {
    int res = ToolRunner.run(new Configuration(), new CountEdges(), args);
    System.exit(res);
  }

}
